<?php

namespace app\models;

use app\traits\ModelTrait;
use Phalcon\Mvc\Collection;


/**
 * Class UserMongo
 * @package app\models
 * @property string $name
 * @property string $username
 * @property string $password
 * @property string $email
 * @property integer $created_at
 * @property string $active
 *
 */
class UserMongo extends Collection
{
    /**
     * @var \MongoDB\Driver\Manager $_connection
     */
    protected $_connection;

    use ModelTrait;

    const COLLECTION = 'blog.user';

    public function initialize()
    {
        $this->_connection = $this->getDI()->getShared('mongo');
    }

    public function getSource()
    {
        return 'users';
    }

    /**
     * 登录功能
     * @param $userName
     * @param $password
     * @param  $captcha
     * @return bool|static 登录失败返回false，并设置错误消息，成功返回用户关联的模型
     */
    public static function login($userName, $password, $code)
    {
        if ($code !== null) {
            $captcha = new \Captcha();
            if (!$captcha->check($code)) {
                self::$error = '验证码错误';
                return false;
            }
        }
        $user = self::find(['username' => $userName]);
        $user = current($user);
        if (!$user) {
            self::$error = '用户名不存在:' . $userName;
            return false;
        }
        $security = new Security();
        if (!$security->checkHash($password, $user->password)) {
            self::$error = '密码错误';
            return false;
        }
        global $application;
        $application->logger->error($user->username);
        $application->session->set('user', [
            'id' => $user->id,
            'username' => $user->username,
            'name' => $user->name
        ]);
        return $user;
    }

    public static function register($user)
    {
        try {
            return $user->save();
        } catch (\Exception $e) {
            self::$error = $e->getMessage();
            $user->getDI()->get('logger')->error($e->getMessage() ."\n" . $e->getTraceAsString());
            return false;
        }
    }

    public function beforeValidation()
    {
        if (empty($this->username)) {
            self::$error = '用户名不能为空';
            return false;
        }
        if (empty($this->password)) {
            self::$error = '密码不能为空';
            return false;
        }
        if (empty($this->email)) {
            self::$error = '邮箱不能为空';
            return false;
        }
        //判断用户名是否符合规则
        $security = new \Security();
        if (!$security->isEmail($this->email)) {
            self::$error = '输入的邮箱格式错误:' . $this->email;
            return false;
        }
        //用户名唯一性判断;
        $user = self::findFirst(['username' => $this->username]);
        if ($user && $user->id != $this->id) {
            self::$error = '用户名已经存在:' . $this->username;
            return false;
        }
        //邮箱唯一判断
        $user = self::findFirst(['email' => $this->email]);
        if ($user && $user->id != $this->id) {
            self::$error = '邮箱已经存在:' . $this->email;
            return false;
        }
        return true;
    }

    public function executeQuery($query)
    {
        $query = new \MongoDB\Driver\Query($query);
        return $this->_connection->executeQuery(self::COLLECTION, $query);
    }

    /**
     * @param array|null $parameters
     * @return \MongoDB\Driver\Cursor mixed
     */
    public static function find(array $parameters = null)
    {
        $model = new static();
        return $model->executeQuery($parameters);
    }
}